from . import user_blue
from flask import *
from info.models import *
from info.utils import validate_request as vr

#用户新闻发布
@user_blue.route('/user/user_news_release',methods=['post','get'])
def user_news_release_handler():
    user = User.query.filter(User.id==session.get('user_id')).first()
    categorys = Category.query.all()
    if request.method == 'GET':
        return render_template(
            'news/user_news_release.html',
            user=user,
            categorys=categorys,
        )
    else:
        title = request.form.get('title')
        category_id = int(request.form.get('category_id'))
        summary = request.form.get('digest')
        body = request.form.get('content')
        file = request.files['index_image']
        if not file:
            return vr.error
        file_error = vr.v_file(file)
        if file_error: return file_error
        basepath = 'info/static/news_image/'
        # 保存图片，格式统一为png
        file.save(basepath + user.uid + '.png')
        # 文件获取路径
        image_url = '/static/news_image/' + title + '.png'
        news = News(title=title, summary=summary, body=body, user_id=user.id, category_id=category_id,image_url=image_url )
        try:
            db.session.add(news)
            db.session.commit()
            # 刷新，不然报错=======就这么用，不懂为啥
            db.session.merge(news)
            db.session.refresh(news)
            # ======================================
        except:
            db.session.rollback()
            return vr.failure
        return vr.sucess


